package com.xnf.ssmweb.controller;

import com.xnf.ssmweb.domain.Permission;
import com.xnf.ssmweb.domain.Role;
import com.xnf.ssmweb.service.PermissionService;
import com.xnf.ssmweb.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chendx on 2021/3/30.
 */

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    @RequestMapping("/toRole")
    @Secured("ROLE_ROOT")
    public ModelAndView toRole(){
        ModelAndView mav = new ModelAndView();
        List<Role> roles = roleService.queryRoles();
        mav.addObject("roles",roles);
        mav.setViewName("role-list");
        return mav;
    }

    @RequestMapping("/toRoleById")
    public ModelAndView toRoleById(Long id){
        ModelAndView mav = new ModelAndView();
        Role role = roleService.queryRoleById(id);
        mav.addObject("role",role);
        mav.setViewName("role-show");
        return mav;
    }

    @RequestMapping("/saveRole")
    public ModelAndView saveRole(Role role){
        ModelAndView mav = new ModelAndView();
        boolean flag = roleService.saveRole(role);
        if (flag) mav.setViewName("redirect:/role/toRole");
        else mav.setViewName("/role-add");
        return mav;
    }

    @RequestMapping("/toRoleByIdAndAllPermission")
    public ModelAndView toRoleByIdAndAllPermission(Long id){
        ModelAndView mav = new ModelAndView();
        List<Permission> permissions = permissionService.queryPermissions();
        Role role = roleService.queryRoleById(id);
        mav.addObject("role",role);
        mav.addObject("permissions",permissions);
        mav.setViewName("role-permission-add");
        return mav;
    }

    @RequestMapping("/savePermissionToRole")
    public ModelAndView savePermissionToRole(String roleId, @RequestParam(name = "ids",required = true) String[] permissionIds){
        ModelAndView mav = new ModelAndView();
        roleService.savePermissionToRole(roleId,permissionIds);
        mav.setViewName("redirect:/role/toRole");
        return mav;
    }
}
